import React, { Component } from 'react'
import { Modal, Button, Select, message } from 'antd';
import moment from 'moment'
import _ from 'lodash'
import Ajax from './Ajax'
const confirm = Modal.confirm;

const Option = Select.Option;
var baseUrl = __dev__?'/api':'';

// 得到新的区划/机构树
export function getNewTreeData(treeData, curKey, child, key) {
  const loop = (data) => {
    data.forEach((item) => {
      if(key){
        if(curKey == item[key]){
          item.children = child||[];
        }else if(item.children){
          loop(item.children);
        }
      }else{
        if(item.orgId&&curKey == item.orgId||item.areaId&&curKey == item.areaId||item.projectCategoryId&&curKey == item.projectCategoryId){
          item.children = child||[];
        }else if(item.children){
          loop(item.children);
        }
      }
    });
  };
  loop(treeData);
  return treeData;
}
// 查找机构、区划
export function findRowData(treeData, info, key){
  var selected = false;
  const loop = (data) => {
    data.forEach((item) => {
      if(key){
        if(info == item[key]){
          selected = item
        }else if(item.children){
          loop(item.children);
        }
      }else{
        if(item.orgId&&info == item.orgId||item.areaId&&info == item.areaId||item.projectCategoryId&&info == item.projectCategoryId){
          selected = item
        }else if(item.children){
          loop(item.children);
        }
      }
    });
  };
  loop(treeData);
  return selected
}
// 添加机构、区划
export function addRowData(treeData, rowdata, b){
  const loop = (data) => {
    data.forEach((item) => {
      if(item.orgId&&rowdata.orgParentId == item.orgId||item.areaId&&rowdata.areaParentId == item.areaId||item.projectCategoryId&&rowdata.projectCategoryParentId == item.projectCategoryId){
        if(item.children){
          item.children.push(rowdata);
        }else{
          b&&(item.children = [rowdata]);
        }
      }else if(item.children){
        loop(item.children);
      }
    });
  };
  loop(treeData);
}
// 删除区划、机构
export function removeRowData(treeData, id){
  const loop = (data) => {
    var find = _.remove(data, (item)=>{
      return item.orgId&&item.orgId == id||item.areaId&&item.areaId == id||item.projectCategoryId&&item.projectCategoryId == id
    })
    if(find.length > 0){
      return
    }else{
      _.each(data, function(it){
        if(it.children){
          loop(it.children);
        }
      })
    }
  };
  loop(treeData);
}
// 根据字典表code获取名字
export function getNameByCode(config, listKey, code){
  const list = config[listKey];
  if(list){
    var find = _.find(list, (item)=>{
      return item.dictionaryCode == code
    });
    if(find){
      return find.dictionaryName
    }else{
      return '-'
    }
  }else{
    return '-'
  }
}
// 根据state获取状态名
export function getNameByState(config, type, state){
  const list = config[type];
  if(list){
    var find = _.find(list, (item)=>{
      return item.code == state
    });
    if(find){
      return find.mean
    }else{
      return '未知'
    }
  }else{
    return '未知'
  }
}
// 下载文件
export function download(url){
  var link = document.createElement("a");

  link.download = "";
  link.href = baseUrl + url;

  document.body.appendChild(link);
  link.click();

  document.body.removeChild(link);
}
// 下载根据接口地址
export function downloadFile(url, data, config){
    const { start, end } = config||{};
    start&&start();
    Ajax({
      url: url,
      data: data?data:{},
      success: function(data){
        download(data);
        end&&end();
      },
      error: function(error){
        message.error(error);
        end&&end();
      }
    });
  }
// 确认框
export function confirmDelete(doIt, cancel, msg){
  confirm({
    title: msg||'确定要删除吗?',
    content: '',
    onOk() {
      doIt()
    },
    onCancel() {
      cancel()
    },
  });
}
// 根据key-list获取obj-list
export function getArrayByValue(list, arr, key){
  var backArr = [];
  _.each(arr, (item)=>{
    var it = {};
    var find = _.find(list, (li)=>{
      return li[key] == item
    })
    find&&backArr.push(find)
  });
  return backArr
}
// 根据key获取key-list
export function getArrayByKey(arr, str){
  var backArr = [];
  if(arr){
    _.each(arr, (item)=>{
      backArr.push(item[str]+'')
    });
  }
  return _.uniq(backArr)
}
// 获取当前年份
export function getYear(){
  var year = moment().year();
  return [year - 1, year, year + 1];
}
// 获取支付次数
export function getPayCycle(code){
  var num = 0;
  switch(code){
    case '233': num=20; break; 
    case '234': num=4; break; 
    case '235': num=2; break; 
    case '236': num=1; break; 
    default : break; 
  }
  return num
}
// 获取支付下拉dom
export function getPayCycleDom(code){
  var num = getPayCycle(code);
  var arr = [];
  for (var i = 1; i <= num; i++) {
    arr.push(i);
  }
  return (arr.map((v)=>{
    return <Option key={v+""}>{v+""}</Option>
  }))
}
// 人员列表信息 title+api
export function  getStringByType(what, type){
  var back = ""
  if(what == 'url'){
    switch(type){
      case 'total': back = '/projectRegister/listCitizen';break;
      case 'fail': back = '/projectRegister/failList';break;
      case 'rFail': back = '/projectRegister/registFailList';break;
      case 'success': back = '/projectRegister/successList';break;
      case 'financeAuditorRegisterList': back = '/projectRegister/financeAuditorRegisterList';break;
      // case 'townsAuditorWaitCizList': back = '/projectRegister/townsAuditorWaitCizList';break;
      case 'townsAuditorWaitCizList': back = '/projectRegister/listCitizen';break;
      // case 'orgAuditorRegisterList': back = '/projectRegister/orgAuditorRegisterList';break;
      case 'orgAuditorRegisterList': back = '/projectRegister/listCitizen';break;
      default: break;
    }
    return back
  }else if(what == 'title'){
    switch(type){
      case 'total': back = '总登记成功人数列表';break;
      case 'fail': back = '失败人数列表';break;
      case 'rFail': back = '登记失败人数列表';break;
      case 'success': back = '成功人数列表';break;
      case 'financeAuditorRegisterList': back = '批次汇总下登记成功人员';break;
      case 'townsAuditorWaitCizList': back = '乡镇复核';break;
      case 'orgAuditorRegisterList': back = '审批人员';break;
      default: break;
    }
    return back
  }
}
// 返回接口地址
export function  backUrl(url){
  return baseUrl + url
}
// 遍历菜单
function loopMenu(arr, url){
  var back = false;
  const loop = (data, pid) => {
    data.forEach((item) => {
      if(url == item.url){
        back = {
          id: item.id,
          parent: pid||undefined
        };
      }else if(item.children){
        loop(item.children, item.id);
      }
    });
  };
  loop(arr);
  return back;
}
// 查找地址
export function findUrl(menus, url){
  var back = false;
  if(menus&&url){
    _.each(menus, (menu)=>{
      var b = loopMenu(menu.children, url);
      if(b){
        back = {
          menu: menu,
          parent: b.parent,
          id: b.id
        };
      }
    });
  }
  return back;
}
// 校验区划
export function validatorArea(rule, value, callback){
  if (value.areaId) {
    callback();
    return;
  }
  callback('请选择区划');
}
// 校验机构
export function validatorOrg(rule, value, callback){
  if (value.orgId) {
    callback();
    return;
  }
  callback('请选择机构');
}

const widths = {
  batchId: 70,
  summaryId: 180,
  projectId: 75,
  projectName: 150,
  year: 75,
  payCycleCode: 75,
  subsidyCount: 75,
  areaName: 150,
  payObjCode: 75,
  registerFailCount: 90,
  totalCount: 105,
  successCount: 75,
  successMoney: 75,
  failCount: 75,
  failReason: 130,
  state: 150,
  action: 75,
  extStatList: 140
}
// table宽度设置
export function tableWidth(col){
  var width = 0;
  _.each(col, (item)=>{
    var v = widths[item.dataIndex||'key'];
    if (!v) {
      v = 100
    }
    item.width = v;
    width += v;
  });
  return width
} 
// 统计信息
export function statistics(list){
  var totalCount = 0;
  var successCount = 0;
  var failCount = 0;
  var successMoney = 0;
  _.each(list, (item)=>{
    item.totalCount&&(totalCount += item.totalCount);
    item.successCount&&(successCount += item.successCount);
    item.failCount&&(failCount += item.failCount);
    item.successMoney&&(successMoney += item.successMoney);
  });
  if(successCount>0&&parseInt(successMoney) != successMoney){
    successMoney = successMoney.toFixed(2);
  }
  return `总登记成功人数${totalCount}，成功人数${successCount}，失败人数${failCount}，总金额${successMoney}`
}
// 图标颜色序列
export function mapColor(){
  return [
        '#39C558',
        '#00b4ff',
        '#FFBE41',
        '#ff3e43',
        '#937fc7',
        
        '#A4BDAC',
        '#D58173',
        '#6493A8',
        '#DBDA63',
        '#AE9A93'
    ]
}
// 条件判断
function isEqualArray(arr1, arr2){
  var back = false;
  if(arr1 == undefined&&arr2 == undefined){
    back == true;
  }else if(_.isArray(arr1)&&_.isArray(arr2)&&arr1.length == arr2.length){
    back = true;
    _.each(arr1, (item)=>{
      if(_.indexOf(arr2, item) < 0){
        back = false 
      }
    })
  }
  return back
}
export function isEqual(next, that){
  var back = true;
  if(!_.isEqual(next, that)){
    back = false;
  }
  if(isEqualArray(next.projectCategoryIds, that.projectCategoryIds)||isEqualArray(next.projectIds, that.projectIds)||isEqualArray(next.areaIds, that.areaIds)||isEqualArray(next.states, that.states)){
    back = false;
  }
  return back
}

// 扩展属性遍历
export function renderExt(list){
  if(list&&list.length>0){
    return list.map((item, i)=>{
      return <span key={item.extId}>{item.extName}:{item.extContent||item.extCalculate||0}{i==list.length-1?"":";"}</span>
    })
  }else{  
    return ""
  }
}
